<template>
	<view>
		<view v-if="show" class="position-fixed top-0 left-0 right-0 bottom-0 flex align-center justify-center bg-light" style="z-index: 100;">
			<text class="font text-muted">加载中...</text>
		</view>
		<view class="px-4">
			<input type="text"  v-model="form.username" class="uni-input bg-light rounded mb-4" placeholder="手机号/用户名/邮箱"/>
			<input type="text" v-model="form.password" class="uni-input bg-light rounded mb-4" placeholder="请输入密码"/>
			<input  v-if="type === 'reg'" type="text" v-model="form.repassword" class="uni-input bg-light rounded mb-4" placeholder="请输入确认密码"/>
			
			<view class="bg-main text-white flex align-center justify-center font-md py-2 rounded-circle" hover-class="bg-main-hover" @click="submit">{{ type === 'login' ? '登 录' : '注 册' }}</view>
		</view>
		<view class="flex align-center justify-center pt-5">
			<view class="text-muted mx-2 font-sm" @click="changeType">
				{{ type === 'login' ? '注册账号' : '去登录' }}
			</view>
		</view>
		
	</view>
</template>

<script>
	import { login,reg } from '../../api/login.js'
	export default {
		data() {
			return {
				form:{
					username: '',
					password: '',
					repassword: ''
				},
				type: 'login',
				show: false
			}
		},
		async onLoad() {
			
		},
		methods: {
			changeType() {
				this.type = this.type ===  'login' ? 'reg' : 'login'
				// 请求输入的数据
				for (let key in (this.form)){
					this.form[key] = ''
				}
			},
			async submit() {
				let msg = this.type === 'login' ? '登录' : '注册'
				// 进行请求 后端已经做了参数验证了，前端部分可以不写验证
				// 登录逻辑
				if(this.type == 'login'){
					let res = await login(this.form)
					this.handleTips('登陆成功',()=>{
						this.$store.dispatch('login',res)
						wx.switchTab({
							url:'../index/index'
						})
					})
				}else{
					// 注册
					let res = reg(this.form)
					this.handleTips('注册成功', ()=>{
						this.type = 'reg'
						this.changeType()
					})
				}
			},
			// 登录提醒
			handleTips(msg, callback) {
				wx.showToast({
					title: msg,
					icon:'none',
					success: ()=>{
						callback && callback()
					}
				})
			}
			
		}
	}
</script>

<style>

</style>
